package it.mbus.component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.Environment;
import android.util.Log;

/**
 * Class contains all the methods working with the remote service that manage
 * the users
 * 
 * @author Fbihack
 * 
 */
public class UserComponent {

	private static final String urls = "http://www.edev.it/ipuffisonoblu/service.php";
	static BufferedReader reader = null;
	static StringBuilder stringBuilder = null;
	static String line = null;

	
	/**
	 * MEthod registers user into remote system
	 */
	public static boolean register(String nomeUtente, String nomeVero, String cognome, String mail, String psw) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(urls);
		String result="";
		try {
		    // Add your data
			//http://www.edev.it/ipuffisonoblu/service.php?operation=register&uname=pippo&passw=12345&name=Gio&surname=franco&email=asd@asd2.it
			List<NameValuePair> nameValuePairs= new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("operation", "register"));
		    nameValuePairs.add(new BasicNameValuePair("uname", nomeUtente));
		    nameValuePairs.add(new BasicNameValuePair("name", nomeVero));
		    nameValuePairs.add(new BasicNameValuePair("surname", cognome));
		    nameValuePairs.add(new BasicNameValuePair("email", mail));
		    String psw2= toMD5(psw);
		    nameValuePairs.add(new BasicNameValuePair("passw", psw2));//asd

		    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

		    // Execute HTTP Post Request
		    HttpResponse response = httpclient.execute(httppost);
		    HttpEntity entity = response.getEntity();
		    if(entity != null){
		    InputStream inputStream = entity.getContent();
		    result = convertStreamToString(inputStream);
		    }
		} catch (Exception e) {
		  	//there was an error, connectivity or anything else
			//Log.d("ERR", e.getMessage());
		  }
		if(result.contains("ERR_NICK"))
			//USERNAME ALREADY EXISTS, HANDLE!
		  	return false;
		if(result.contains("ERR_EMAIL"))
			//EMAIL ALREADY EXISTS, HANDLE!
		  	return false;
		if(result.contains("OK"))
			return true; //EVERYTHING WORKED FINE!
		else
			return false; //Some unexpected error!
	}
	
	public static String toMD5(String md5) {
		   try {
		        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
		        byte[] array = md.digest(md5.getBytes());
		        StringBuffer sb = new StringBuffer();
		        for (int i = 0; i < array.length; ++i) {
		          sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
		       }
		        return sb.toString();
		    } catch (java.security.NoSuchAlgorithmException e) {
		    }
		    return null;
		}
	
	public static boolean login(String u,String a) {
		String p=toMD5(a);
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(urls);
		String result = "";
		try {
			// Add your data
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("operation", "slogin"));
			nameValuePairs.add(new BasicNameValuePair("uname", u));
			nameValuePairs.add(new BasicNameValuePair("passw", p));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream inputStream = entity.getContent();
				result = convertStreamToString(inputStream);
			}
		} catch (Exception e) {
			// there was an error, connectivity or anything else
			// Log.d("ERR", e.getMessage());
			System.out.println();
		}
		if (result.contains("1"))
			

			return true; // WE ARE LOGGED IN
		else
			// UNAME OR PASS IS WRONG
			return false;
	}

	

	public static String leggiDati() {
		File folder = new File(Environment.getExternalStorageDirectory()
				.toString() + "/mBus");
		String extStorageDirectory = folder.toString();
		File file = new File(extStorageDirectory, "logU.mbs");
		//Read text from file
		StringBuilder text = new StringBuilder();

		try {
		    BufferedReader br = new BufferedReader(new FileReader(file));
		    String line;

		    while ((line = br.readLine()) != null) {
		        text.append(line);
		        text.append('\n');
		    }
		}
		catch (IOException e) {
		    //You'll need to add proper error handling here
		}
		return text.toString();
	}

	public static void salvaDatiUtente(String u, String md5) {

		File folder = new File(Environment.getExternalStorageDirectory()
				.toString() + "/mBus");

		// Save the path as a string value
		String extStorageDirectory = folder.toString();

		// Create New file and name it logU.mbs
		File file = new File(extStorageDirectory, "logU.mbs");
		FileWriter f = null;
		PrintWriter p = null;
		// BufferedWriter b = null;
		try {
			f = new FileWriter(file, false);
			p = new PrintWriter(f);
			// p.println(u+"!i!"+md5);
			p.println(u + "!i!" + md5);
			p.close();
			f.close();

		} catch (IOException e) {
			e.printStackTrace();
			// Toast.makeText(context, "Attenzione ERRORE:" +
			// e.toString(),Toast.LENGTH_SHORT).show();
		}
	}

	public static String convertStreamToString(InputStream is) throws Exception {

		reader = new BufferedReader(new InputStreamReader(is));

		stringBuilder = new StringBuilder();

		try {
			while ((line = reader.readLine()) != null) {
				stringBuilder.append(line + "\n");
			}
		} finally {
			is.close();
		}
		return stringBuilder.toString();
	}
}
